package com.hjtech.baselib.utils

import android.content.Context
import android.util.DisplayMetrics
import android.view.WindowManager

import java.lang.ref.WeakReference

/**
 * TODO 单例模式 获取屏幕宽高的帮助类
 */

class ScreenSizeUtils private constructor(mContext: Context) {
    //获取屏幕宽度
    val screenWidth: Int
    //获取屏幕高度
    val screenHeight: Int
    private val context: Context

    init {
        val contextWeakReference = WeakReference(mContext)
        context = contextWeakReference.get()!!
        val manager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val dm = DisplayMetrics()
        manager.defaultDisplay.getMetrics(dm)

        screenWidth = dm.widthPixels// 获取屏幕分辨率宽度
        screenHeight = dm.heightPixels

    }

    /**
     * 根据手机的分辨率从 dip 的单位 转成为 px(像素)
     *
     * @return px
     */
    fun dip2px(dpValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }

    companion object {

        private var instance: ScreenSizeUtils? = null


        fun getInstance(mContext: Context): ScreenSizeUtils? {
            if (instance == null) {
                synchronized(ScreenSizeUtils::class.java) {
                    if (instance == null)
                        instance = ScreenSizeUtils(mContext)
                }
            }
            return instance
        }
    }
}
